#include "sendpackthread.h"
#include "Protocol.h"
#include <QDebug>

SendPackThread::SendPackThread(QSerialPort *port)
{
    m_port = port;
    //moveToThread(this);  // 将线程内的 QSerialPort 移到当前线程中
}

void SendPackThread::run()
{
    //命令，参数集
    unsigned char cmd_and_parameter[][2] ={
        {ZHU_JI_WEN_DU_REQ,0},
        {ZHOU_SU_DU_REQ,1},
        {ZHOU_SU_DU_REQ,2},
        {GANG_YOU_LIANG_REQ,1},
        {GANG_YOU_LIANG_REQ,2},
        {GANG_YOU_LIANG_REQ,3},
        {YA_LI_CANG_REQ,1},
        {YA_LI_CANG_REQ,2},
        {YA_LI_CANG_REQ,3},
        {YA_LI_CANG_REQ,4},
        {YA_LI_CANG_REQ,5},
        {JI_XIE_BI_REQ,0}
        //其他命令...
    };

    //发包
    char pack[9];
    char data[4] = {0,0,0,0};
    int cmdCount = sizeof(cmd_and_parameter)/sizeof(cmd_and_parameter[0]);
    while(1)
    {
        for(int i = 0;i<cmdCount;i++)
        {
            if(buildPack(cmd_and_parameter[i][0],cmd_and_parameter[i][1],data,pack)) //组装
            {
                //发送
                int ret = m_port->write(pack,sizeof(pack));
                qDebug() << "send " << ret << " bytes.";
                m_port->waitForBytesWritten(100);
                QThread::msleep(500);
            }
        }
    }
}

bool SendPackThread::buildPack(char cmd,char param,char data[],char *pack)
{
    if(!pack) return false;

    pack[0] = 0xEF;
    pack[1] = cmd;
    pack[2] = param;
    pack[3] = data[0];
    pack[4] = data[1];
    pack[5] = data[2];
    pack[6] = data[3];

    //奇偶检验位用偶检验（与下位机保持一致）
    int count = 0;

    for(int k = 1;k<=6;k++)
    {
        char byte = pack[k];
        for(int i = 0;i<8;i++)
        {
            if(byte & 1) count++; // byte最低位与运算
            byte >>= 1;
        }
    }
    if(count & 1)
        pack[7] = 1;
    else
        pack[7] = 0;


    pack[8] = 0xFE;

    return true;
}
